/*
*    FileName: realplay.cpp
* Description: realplay
*     Version: 1.0
*      Author: wulin
* Modification History
*    2011-6-21 wulin  Modify for use on windows.
*/
#include "realplay.h"
#include <QTimer>
#include <QDateTime>
#include <QMessageBox>
#include <QApplication>
#include <QDebug>
#include <QUdpSocket>
#include <QLibrary>
#include <QTimer>
#include <QSqlQuery>
#include <QSqlError>
#include "db.h"
#include "searchtimeset.h"
#include "ui_searchtimeset.h"
#include "ui_settingsdialog.h"
#include "playctrl.h"
#include "settingsdialog.h"
#include "PlayM4.h"
#include "macro.h"
#include "debuginfo.h"
#include "ui_debuginfo.h"
#include "ONSClient/onsmessenger.h"
#include "VideoHik.h"
//#define debu  //determine whether to qdebug()

#define serverPort 6789  //服务器UDP端口

/*******************************************************************
      Function:   RealPlay::RealPlay
   Description:   ????

        Return:   none
**********************************************************************/
RealPlay::RealPlay(QWidget *parent): QDialog(parent)
{
    udpSocket=new QUdpSocket(this);
    dbo=new databaseOperation(this);
    onsMsger=new ONSMessenger(ONS_CLIENT_NAME,this);
    blockUdpSocket=new QUdpSocket(this);

    settingsDialog=new SettingsDialog(this);
    blockUdpSocket->connectToHost(QHostAddress(ONS_IP),ONS_PORT);

    myDebugInfo=new DebugInfo(this);

    ui.setupUi(this);

    initFrameIndex();

    port0Used=false; port10Used=false;
    port1Used=false;port2Used=false;
    port3Used=false;

    //Qt::WindowFlags flags =Qt::Widget|Qt::CustomizeWindowHint|Qt::WindowMinMaxButtonsHint|Qt::WindowCloseButtonHint|Qt::WindowStaysOnTopHint;
    Qt::WindowFlags flags =Qt::Widget|Qt::CustomizeWindowHint|Qt::WindowStaysOnTopHint;

    setWindowFlags(flags);

    close=true;
    settingsDialog->exec();
    timeEdit=new SearchTimeSet(this);

    ui.groupBoxPlayBack->hide();
    show();

    serverIP=settingsDialog->ui->lineEditHost->text(); //must before playctrl

    playCtrl=new PlayCtrl(this); //这条语句必须在realPlay的serverIP变量初始化后再调用

    newPlayBack=false;
    horizonValueApplied=false;
    playB=new QTime;
    playE=new QTime;

    udpSocket->bind(); //client端口。可以是任意大于1024的
    connect(udpSocket,SIGNAL(readyRead()),
           this,SLOT(processPendingDatagrams()));

//PlayM4_InitDDraw(m_pframePlay->winId());

       // INITINFO info; info.uWidth=m_pframePlay->width();
       // info.uHeight=m_pframePlay->height();
#ifdef debu
        //qDebug()<<"PlayM4_Init"<<PlayM4_Init(info,1);
        //qDebug()<<"PlayM4_Init error:"<<PlayM4_GetLastErrorCode();
#else
           //PlayM4_Init(info,1);
#endif

     connect(qApp,SIGNAL(aboutToQuit()),this,SLOT(almostQuit()));

     lib.setFileName("PlayCtrl");

     if(lib.load())
     {
         qDebug()<<"dll loaded successfully";
         funStop = (myStop)lib.resolve("PlayM4_Stop");//用resolve来解析
         funSetStreamOpenMode=(mySetStreamOpenMode)lib.resolve("PlayM4_SetStreamOpenMode");
         funInputData=(myInputData)lib.resolve("PlayM4_InputData");
        funCloseStream=(myCloseStream)lib.resolve("PlayM4_CloseStream");
        funFreePort=(myFreePort)lib.resolve("PlayM4_FreePort");
        funGetPort=(myGetPort)lib.resolve("PlayM4_GetPort");
        funOpenStream=(myOpenStream)lib.resolve("PlayM4_OpenStream");
        funPlay=(myPlay)lib.resolve("PlayM4_Play");
        //qDebug()<<"funplay is"<<funPlay;
        funSetColor=(mySetColor)lib.resolve("PlayM4_SetColor");
        funGetLastError=(myGetLastError)lib.resolve("PlayM4_GetLastError");
        funSetPicQuality=(mySetPicQuality)lib.resolve("PlayM4_SetPicQuality");
    }


     sensorIDList.append(0);     sensorIDList.append(0);
     sensorIDList.append(0);    sensorIDList.append(0);

     pixmapList.append(new QPixmap);     pixmapList.append(new QPixmap);
     pixmapList.append(new QPixmap);     pixmapList.append(new QPixmap);

     timeElapForInpt.append(new QTime); timeElapForInpt.append(new QTime);
     timeElapForInpt.append(new QTime); timeElapForInpt.append(new QTime);

     timeElapForInpt.at(0)->start(); timeElapForInpt.at(1)->start();
     timeElapForInpt.at(2)->start(); timeElapForInpt.at(3)->start();

    timerForRead= new QTimer(this);
    connect(timerForRead, SIGNAL(timeout()), this, SLOT(readDatabase()));
    readDataBaseGap=1000;
     timerForRead->start(readDataBaseGap);

     timeForNetWorkMeasure.start();

     timeElapsedForInputData.start(); //启动用于帧率控制的时钟。当前主要用于MJPEG的帧率控制

     connect(&timerForInputData,SIGNAL(timeout()),this,SLOT(timerFunctionForInputData()));

     toConnectFrameCtrl();  //连接播放窗口frame的一些信号
}


void RealPlay::readDatabase()
{
    if(playCtrl->onRealPlay&&QTime::currentTime().second()%15==0) //every 20 seconds
	{
       	 udpSocket->writeDatagram("Video Alive",QHostAddress(serverIP),serverPort);
		udpSocket->writeDatagram("INFO：For Punching",QHostAddress(serverIP),6788);
	}

    if(!playCtrl->onSearch)
        return;  //如果不是检索状态，则结束

    timeForNetWorkMeasure.restart();

   QTime currentPlayTime;
   quint16 histroyRate=timeEdit->rowRate; //定时器是1s

   bool ok;
   qDebug()<<"history rate:"<<histroyRate;
   qDebug()<<*playB<<*playE;

 /*
    0号窗口历史检索
    */
    if(playCtrl->hasBegun&&(playCtrl->onSearch&&ui.timeEditCurrent->time()<*playE))
    {
        if(ui.frame0->isVisible())//search
            dbo->query->exec("select SensorData,ID,DateTime,SensorID,SN from "+timeEdit->tableNameForHistory+" where id>= "
                        +QString::number(videoID)+"  and id<"+QString::number(videoID+histroyRate,10));

        qDebug()<<"tableNameForHistory is:"<<timeEdit->tableNameForHistory<<"videoID is"<<videoID<<
                "HistoryRate is:"<<histroyRate;
        quint8 SN;

        while(dbo->query->next()&&playCtrl->hasBegun==true&&(playCtrl->onSearch&&currentPlayTime!=*playE))
        {
            currentPlayTime=dbo->query->value(2).toDateTime().time();
            ui.timeEditCurrent->setTime(currentPlayTime);
            QByteArray packet=dbo->query->value(0).toByteArray();
            SN=dbo->query->value(4).toUInt(&ok);
            dataList0.append(packet);

            if(dbo->query->value(3).toUInt(&ok)!= sensorIDList.at(0))
            {
                sensorIDList.replace(0,dbo->query->value(3).toUInt(&ok));
            }
            ++videoID;
        }

        if(playCtrl->onSearch)  //历史回放，固定用10号解码端口
        {
            if(currentPlayTime>=*playE&&playCtrl->hasBegun==true) //如果播放到头，则结束播放，
            {
                funStop(10);
                funCloseStream(10);
               playCtrl->hasBegun=false;
            }
            else if(horizonValueApplied)  //to make sure value change by user to the horizon is applied
            {
                quint64 sec=playB->secsTo(currentPlayTime);
                int num=sec*100/secondsOfPlayback;
                if(num>ui.horizontalSlider->value()&&num<100)
                    ui.horizontalSlider->setValue(num);
            }
            else
            {
                horizonValueApplied=true;
            }
        }
    }

     quint16 timeElapse=timeForNetWorkMeasure.elapsed();

     myDebugInfo->ui->plainTextEdit->appendPlainText("timeElapsed for read DB is "+
         QString::number(timeElapse)+'\n');
     myDebugInfo->ui->plainTextEdit->appendPlainText("raedDatabaseGap is "+
         QString::number(readDataBaseGap)+'\n');

     if(timeElapse<1000*maxPercantage)  //网络速度足够好
     {
         readDataBaseGap=1000;
         return;
     }
     //当前读取间隔太小了。读取间隔不当大于5s
     else if(timeElapse>readDataBaseGap*maxPercantage&&readDataBaseGap<5000)
     {
         readDataBaseGap*=2;
         timerForRead->start(readDataBaseGap);
     }
     else if(timeElapse<readDataBaseGap*minPercantage&&readDataBaseGap>=1900)
     {
         readDataBaseGap=readDataBaseGap/2.0;
         timerForRead->start(readDataBaseGap);
     }
}

/*******************************************************************
      Function:   RealPlay::openPort
   Description:   get play port
     Parameter:   (IN)   none
         -----wulin
**********************************************************************/
void RealPlay::openPort()
{
    bool ok;
    dataList0.clear();
    QString tableNameTemp;
    QByteArray packet;
    quint32 sensorID;

    qDebug()<<"opening port";

    if(playCtrl->onRealPlay)
    {
        for(int n=0;n<4;n++)
        {
            tableNameTemp=settingsDialog->tableNameList.at(n);
            qDebug()<<tableNameTemp;
            if(!tableNameTemp.isEmpty())
            {
                if(! (dbo->query->exec("select SensorData,ID,SensorID from "+tableNameTemp+" where ID="
                                       "(select max(ID) from "+tableNameTemp+" where beginend='b')") )  )
                    qDebug()<<"select SensorData fail.Please check RealPlay::openPort()"<<dbo->query->lastError();
                else if(dbo->query->next())
                {
                    sensorID=dbo->query->value(2).toUInt(&ok);
                    sensorIDList.replace(n,sensorID);

                    if(sensorID!=sensorIDHik)
                        continue; //不是海康视频，无需起始帧
                    else //海康视频
                    {
                        packet=dbo->query->value(0).toByteArray();
                        if(packet.size()!=VideoHikHead.size())
                            packet=VideoHikHead; //如果查找起始帧出错，则使用默认值
                    }
                }
                else //没有找到beginend=‘b’的项
                {
                    if(! (dbo->query->exec("select SensorID from "+tableNameTemp+" where ID="
                                           "(select max(ID) from "+tableNameTemp+")") )  )
                        qDebug()<<"select SensorID fail.Please check RealPlay::openPort()"<<dbo->query->lastError();
                    else if(dbo->query->next())
                    {
                        sensorID=dbo->query->value(0).toUInt(&ok);
                        sensorIDList.replace(n,sensorID);

                        if(sensorID!=sensorIDHik)
                            continue; //不是海康视频，无需起始帧
                        else //海康视频
                        {
                            packet=VideoHikHead; //如果查找起始帧出错，则使用默认值
                        }
                    }
                 }
                sensorIDList.replace(n,sensorID);
                myRealDataCallBack(packet,n);
                playCtrl->hasBegun=true; //palyer has been ready for play
            } //if(!tableNameTemp.isEmpty()) ends
        } //for ends
    }//if(playCtrl->onRealPlay) ends
    else
    {
        tableNameTemp=timeEdit->tableNameForHistory;
        if(!tableNameTemp.isEmpty())
        {
            if(! (dbo->query->exec("select SensorData,ID,SensorID from "+tableNameTemp+" where ID="
                                   "(select max(ID) from "+tableNameTemp+" where beginend='b')") )  )
                qDebug()<<"select SensorData fail.Please check RealPlay::openPort()";
            else if(dbo->query->next())
            {
                quint32 sensorID=dbo->query->value(2).toUInt(&ok);
                QByteArray packet;
                if(sensorID!=sensorIDHik)
                    return; //不是海康视频，无需起始帧
                else //海康视频
                {
                    packet=dbo->query->value(0).toByteArray();
                    if(packet.size()!=VideoHikHead.size())
                        packet=VideoHikHead; //如果查找起始帧出错，则使用默认值
                }

                dataList0.append(packet);
                sensorIDList.replace(0,dbo->query->value(2).toUInt(&ok));
                //myRealDataCallBack(packet,10);
                playCtrl->hasBegun=true; //palyer has been ready for play
            }
            else
            {
                if(! (dbo->query->exec("select SensorID from "+tableNameTemp+" where ID="
                                       "(select max(ID) from "+tableNameTemp+")") )  )
                    qDebug()<<"select SensorID fail.Please check RealPlay::openPort()"<<dbo->query->lastError();
                else if(dbo->query->next())
                {
                    sensorID=dbo->query->value(0).toUInt(&ok);
                    if(sensorID!=sensorIDHik)
                        return; //不是海康视频，无需起始帧
                    else //海康视频
                    {
                        packet=VideoHikHead; //如果查找起始帧出错，则使用默认值
                    }
                    dataList0.append(packet);
                    sensorIDList.replace(0,sensorID);
                    playCtrl->hasBegun=true; //palyer has been ready for play
                }
            }

        }
    }
}

/*******************************************************************
      Function:   RealPlay::~RealPlay
   Description:
     Parameter:   (IN)   none
**********************************************************************/
RealPlay::~RealPlay()
{

  stopRealPlay();

#ifdef __linux__
    //NET_DVR_DrawAreaRelease();
#endif

}



/************************************************************************
 *        Function            :  stopRealPlay
 *        Description         :  stop real play
 *        Input               :  ?????
 *        Output              :  none
 *        Return              :  none
*************************************************************************/
void RealPlay::stopRealPlay()
{

//	stopRealPlayEncapseInterface();
    //m_pframePlay->hide(); //If don't do this, the window is black.
    //m_pframePlay->show();
}


void RealPlay::myRealDataCallBack( QByteArray &videoData,quint8 playPort)
{

    quint8 index=playPort;
    if(index==10)
        index=0;
   // qDebug()<<"sensorid is"<<sensorIDList.at(index);

    if(sensorIDList.at(index)==12) //MJPEG
    {
        showMJPEGVideo(videoData,index);
        return;
    }

    DWORD dwDataType;
    DWORD dwBufSize;
    bool ok;

    dwDataType=videoData.mid(0,1).toHex().toLongLong(&ok,16);
    videoData.remove(0,4);

    dwBufSize=videoData.size();

#ifdef debu
    qDebug()<<"dwDataType:"<<dwDataType<<" dwBufSize:"<<dwBufSize;
    qDebug()<<"first  byte:"<<videoData.mid(0,1).toHex();
     qDebug()<<"last  byte:"<<videoData.mid(videoData.size()-1,1).toHex();

#endif


    /*HWND handle;handle.uHeight=m_framePlayWnd[0]->height();
    handle.uWidth=m_framePlayWnd[0]->width();
    handle.x=m_framePlayWnd[0]->x();handle.y=m_framePlayWnd[0]->y();*/
   //  HWND handle;handle.uHeight= m_pframePlay->height();
   //      handle.uWidth= m_pframePlay->width();
    //     handle.x= m_pframePlay->x();handle.y= m_pframePlay->y();


    switch(dwDataType)
    {
    case 1: //

/*
         if(playCtrl->hasBegun) //if is opened ,stop first
        {
             if(port0Used&&playPort==0)
             {
                break;
             }
             else if(port1Used&&playPort==1)
             {
                 break;
             }
             else if(port2Used&&playPort==2)
             {
                 break;
             }
             else if(port3Used&&playPort==3)
             {
                 break;
             }
             else if(port10Used&&playPort==10)
             {
                // playCtrl->hasBegun=false;//如果正在播放中，且遇到了系统头，则认为播放结束，停止播放
                 break;
             }

        }
*/

        if (dwBufSize > 1)
        {
            //if (!PlayM4_SetOpenStreamMode(lPort, STREAME_REALTIME))  //????

            if (!funSetStreamOpenMode(playPort, STREAME_REALTIME))  //????
            {
#ifdef debu
                qDebug()<<"SetStreamOpenMode error";
#endif
                break;
            }

            quint32 streamBufSize=(settingsDialog->ui->comboBoxDelay->currentIndex()*4+1)*50*1024;
           //if (!PlayM4_OpenStream(lPort, videoData.data(), dwBufSize, streamBufSize)) //?
            if (!funOpenStream(playPort, videoData.data(), dwBufSize, streamBufSize)) //?
                //if (!mOpenStream(lPort, a, dwBufSize, 1024*1024)) //?

            {
#ifdef debu
                qDebug()<<"OpenStream error:";
                qDebug()<<funGetLastError(playPort);
#endif
                break;
            }


            //if (!PlayM4_Play(lPort, handle)) //??
             //if (!funPlay(lPort,m_pframePlay->winId()))
            if(playPort==0)
            {
                funPlay(playPort,ui.frame0->winId());
                port0Used=true;
            }
            else if(playPort==1)
            {
                funPlay(playPort,ui.frame_1->winId());
                port1Used=true;
            }
            else if(playPort==2)
            {
                funPlay(playPort,ui.frame_2->winId());
                port2Used=true;
            }
            else if(playPort==3)
            {
                funPlay(playPort,ui.frame_3->winId());
                port3Used=true;
            }
            else if(playPort==10)
            {
                funPlay(playPort,ui.frame0->winId());
                port10Used=true;
            }

                break;

         }

            break;

     case 2:
     case 4:   //
     case 5:
         if (dwBufSize > 0 )
         {
             //if (!PlayM4_InputData(lPort, videoData.data(), dwBufSize))
              if (!funInputData(playPort, videoData.data(), dwBufSize))

             {
                 #ifdef debu
                 qDebug()<<"playPort:"<<playPort<<"  dwBufSize:"<<dwBufSize<<" first 8 bytes: "<<videoData.mid(0,8).toHex();
                 #endif
                 break;
             }
         }
     }
/*
    #ifdef debu
    qDebug()<<"last error:"<<funGetLastError(playPort);
     qDebug()<<"----------end---------------\n";
    #endif
     */
}

void RealPlay::processPendingDatagrams()
{
    QByteArray datagram;
    QHostAddress hostIP;
    quint16 hostPort;
    bool ok;
    /***************数据包解析****************************/
    do
    {
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(),datagram.size(),&hostIP,&hostPort); //读数据包

        if(hostPort==ServerPortVideo) //如果是视频
        {
            if(!datagram.startsWith("INF")&&!datagram.startsWith("WAR")&&!datagram.startsWith("ERR"))
            {
                quint64  videoMac=datagram.mid(0,MAC_BYTES).toHex().toULongLong(&ok,16);
                datagram.remove(0,MAC_BYTES);
                quint8 sN=datagram.mid(0,SN_BYTES).toHex().toLongLong(&ok,16);
                datagram.remove(0,SN_BYTES);
                quint8 sensorID=datagram.mid(0,SENSORID_BYTES).toHex().toLongLong(&ok,16);
                datagram.remove(0,SENSORID_BYTES);

                ui.timeEditCurrent->setTime(QTime::currentTime());

                if(ui.frame0->macAddr==videoMac&&ui.frame0->isVisible())
                {
                    sensorIDList.replace(0,sensorID);
                    myRealDataCallBack(datagram,0);
                }
                if(ui.frame_1->macAddr==videoMac&&ui.frame_1->isVisible())
                {
                    sensorIDList.replace(1,sensorID);
                    myRealDataCallBack(datagram,1);
                }
                if(ui.frame_2->macAddr==videoMac&&ui.frame_2->isVisible())
                {
                    sensorIDList.replace(2,sensorID);
                    myRealDataCallBack(datagram,2);
                }
                if(ui.frame_3->macAddr==videoMac&&ui.frame_3->isVisible())
                {
                    sensorIDList.replace(3,sensorID);
                    myRealDataCallBack(datagram,3);
                }
            }
        }
        else
            qDebug()<<datagram;
    }while (udpSocket->hasPendingDatagrams());
}

void RealPlay::toConnectFrameCtrl()
{
    connect(ui.frame0,SIGNAL(signalShowMaxFrame(int)),this,SLOT(slotShowMax(int)));
    connect(ui.frame_1,SIGNAL(signalShowMaxFrame(int)),this,SLOT(slotShowMax(int)));
    connect(ui.frame_2,SIGNAL(signalShowMaxFrame(int)),this,SLOT(slotShowMax(int)));
    connect(ui.frame_3,SIGNAL(signalShowMaxFrame(int)),this,SLOT(slotShowMax(int)));

    connect(ui.frame0,SIGNAL(signalTurnLeft(quint64,quint16)),playCtrl,SLOT(slotTurnLeft(quint64,quint16)));
    connect(ui.frame0,SIGNAL(signalTurnRight(quint64,quint16)),playCtrl,SLOT(slotTurnRight(quint64,quint16)));
    connect(ui.frame0,SIGNAL(signalTurnUp(quint64,quint16)),playCtrl,SLOT(slotTurnUp(quint64,quint16)));
    connect(ui.frame0,SIGNAL(signalTurnDown(quint64,quint16)),playCtrl,SLOT(slotTurnDown(quint64,quint16)));
    connect(ui.frame0,SIGNAL(signalExpandFocus(quint64,quint16)),playCtrl,SLOT(slotExpandFocus(quint64,quint16)));
    connect(ui.frame0,SIGNAL(signalNarrowFocus(quint64,quint16)),playCtrl,SLOT(slotNarrowFocus(quint64,quint16)));

    connect(ui.frame_1,SIGNAL(signalTurnLeft(quint64,quint16)),playCtrl,SLOT(slotTurnLeft(quint64,quint16)));
    connect(ui.frame_1,SIGNAL(signalTurnRight(quint64,quint16)),playCtrl,SLOT(slotTurnRight(quint64,quint16)));
    connect(ui.frame_1,SIGNAL(signalTurnUp(quint64,quint16)),playCtrl,SLOT(slotTurnUp(quint64,quint16)));
    connect(ui.frame_1,SIGNAL(signalTurnDown(quint64,quint16)),playCtrl,SLOT(slotTurnDown(quint64,quint16)));
    connect(ui.frame_1,SIGNAL(signalExpandFocus(quint64,quint16)),playCtrl,SLOT(slotExpandFocus(quint64,quint16)));
    connect(ui.frame_1,SIGNAL(signalNarrowFocus(quint64,quint16)),playCtrl,SLOT(slotNarrowFocus(quint64,quint16)));

    connect(ui.frame_2,SIGNAL(signalTurnLeft(quint64,quint16)),playCtrl,SLOT(slotTurnLeft(quint64,quint16)));
    connect(ui.frame_2,SIGNAL(signalTurnRight(quint64,quint16)),playCtrl,SLOT(slotTurnRight(quint64,quint16)));
    connect(ui.frame_2,SIGNAL(signalTurnUp(quint64,quint16)),playCtrl,SLOT(slotTurnUp(quint64,quint16)));
    connect(ui.frame_2,SIGNAL(signalTurnDown(quint64,quint16)),playCtrl,SLOT(slotTurnDown(quint64,quint16)));
    connect(ui.frame_2,SIGNAL(signalExpandFocus(quint64,quint16)),playCtrl,SLOT(slotExpandFocus(quint64,quint16)));
    connect(ui.frame_2,SIGNAL(signalNarrowFocus(quint64,quint16)),playCtrl,SLOT(slotNarrowFocus(quint64,quint16)));

    connect(ui.frame_3,SIGNAL(signalTurnLeft(quint64,quint16)),playCtrl,SLOT(slotTurnLeft(quint64,quint16)));
    connect(ui.frame_3,SIGNAL(signalTurnRight(quint64,quint16)),playCtrl,SLOT(slotTurnRight(quint64,quint16)));
    connect(ui.frame_3,SIGNAL(signalTurnUp(quint64,quint16)),playCtrl,SLOT(slotTurnUp(quint64,quint16)));
    connect(ui.frame_3,SIGNAL(signalTurnDown(quint64,quint16)),playCtrl,SLOT(slotTurnDown(quint64,quint16)));
    connect(ui.frame_3,SIGNAL(signalExpandFocus(quint64,quint16)),playCtrl,SLOT(slotExpandFocus(quint64,quint16)));
    connect(ui.frame_3,SIGNAL(signalNarrowFocus(quint64,quint16)),playCtrl,SLOT(slotNarrowFocus(quint64,quint16)));
}

void RealPlay::setHostIP()
{
    //iot://gwict.gw.wsn.tnsroot.cn/monitor/1/网络技术研究中心/计算所
    QString inputURI=settingsDialog->ui->lineEditURI->text();
    QString subURI=inputURI.split("//").at(1);
    QString objName=subURI.split('.').at(0);
    QString objType=subURI.split('.').at(1);
    QString objOwner=subURI.split('/').at(3);
    QString objLoc=subURI.split('/').at(4);

    QByteArray msg=onsMsger->genMesg(objName,objType,objOwner,objLoc,"Query",0,true,"");

    blockUdpSocket->write(msg);
    if(blockUdpSocket->waitForReadyRead(1000))
    {
        onsMsger->analyzeReceivedMsg(blockUdpSocket->readAll());
        if(onsMsger->Status=="200") //200表示查找IP成功
            settingsDialog->ui->lineEditHost->setText(onsMsger->GWIP);
        else
            settingsDialog->ui->lineEditHost->setText(onsMsger->Status+" "+onsMsger->Description);
    }
    else if(blockUdpSocket->waitForReadyRead(2000))
    {
        onsMsger->analyzeReceivedMsg(blockUdpSocket->readAll());
        if(onsMsger->Status=="200") //200表示查找IP成功
            settingsDialog->ui->lineEditHost->setText(onsMsger->GWIP);
        else
            settingsDialog->ui->lineEditHost->setText(onsMsger->Status+" "+onsMsger->Description);
    }
    else
    {
        settingsDialog->ui->lineEditHost->setText("Directory Service Unavailable");
    }

}

void RealPlay::almostQuit()
{
    if(playCtrl->hasBegun)  //停止播放
    {
        if(playCtrl->onSearch)
        {
            funStop(10);
            funCloseStream(10);
        }
        else if(playCtrl->onRealPlay)
        {
            for(int n=0;n<=3;n++)
            {
                if(!settingsDialog->tableNameList.at(n).isEmpty())
                {
                    funStop(n);
                    funCloseStream(n);
                }
            }
        }

    }

    lib.unload();  //卸载解码库
}

void RealPlay::timerFunctionForInputData()
{
    if(!playCtrl->onSearch)
        return;
   // qDebug()<<"Pending datagram number:"<<dataList0.size();
    QByteArray temp;
    if(dataList0.size()==0)
        timerForInputData.start(timerForInputData.interval()*1.06); //播放太快了，降低速度
    else if(dataList0.size()>timeEdit->rowRate*1.2)
        timerForInputData.start(timerForInputData.interval()*0.95);

   if(dataList0.size()>=1)
   {
       if(!ui.frame0->isVisible())
           dataList0.clear();
       if(playCtrl->onSearch)
       {           
           temp=dataList0.at(0);
            myRealDataCallBack(temp,10);
            dataList0.removeFirst();
            if(dataList0.size()>=30) //播放速度有点慢
            {
                temp=dataList0.at(0);
                 myRealDataCallBack(temp,10);
                 dataList0.removeFirst();
            }
       }
   }
}


void  RealPlay::showMJPEGVideo(QByteArray &videoData, quint8 windowIndex)
{
    pixmapList.at(windowIndex)->loadFromData(videoData);

    QList <PlayFrame*>  playFramList;
    playFramList.append(ui.frame0); playFramList.append(ui.frame_1);
    playFramList.append(ui.frame_2);playFramList.append(ui.frame_3);

    playFramList.at(windowIndex)->setPixmap(pixmapList.at(windowIndex)->scaled(playFramList.at(windowIndex)->width(),
           playFramList.at(windowIndex)->height(),Qt::IgnoreAspectRatio));
    //update();
}

void RealPlay::slotTimerQuit()
{
    exit(0);
}

void RealPlay::on_pushButtonShowTime_toggled(bool checked)
{
    if(checked)
    {
        ui.groupBoxPlayBack->show();
        ui.pushButtonShowTime->setText(tr("隐藏时间"));
    }
    else
    {
        ui.groupBoxPlayBack->hide();
        ui.pushButtonShowTime->setText(tr("显示时间"));
    }
}
